package com.terabits.smartriver.job;

import com.terabits.smartriver.mapper.BoxDataMapper;
import com.terabits.smartriver.mapper.DeviceMapper;
import com.terabits.smartriver.meta.dto.MongoData;
import com.terabits.smartriver.meta.po.BoxData;
import com.terabits.smartriver.meta.po.Device;
import com.terabits.smartriver.service.impl.BaseService;
import com.terabits.smartriver.util.MongoManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

import static com.terabits.smartriver.util.DateUtils.*;


@Component
public class CheckBoxDataJob extends BaseService {
    @Autowired
    private DeviceMapper deviceMapper;
    @Autowired
    private BoxDataMapper boxDataMapper;
    @Resource
    private MongoManager mongoManager;

    @Scheduled(cron = "0 10 14 ? * *")
//    @Scheduled(cron = "0 */1 * * * ?")
    public void CheckBoxData() {
        String[] findKeys = {"boxInterface"};
        //获取所有设备
        List<Device> devices = deviceMapper.selectAll();
        for (Device device : devices) {
            String[] findValue = {device.getBoxInterface()};
            String boxNum = device.getBoxNum();
            MongoData one = (MongoData) mongoManager.findOne(new MongoData(), findKeys, findValue, boxNum, "createTime");
            if (!ObjectUtils.isEmpty(one)) {
                BoxData boxData = new BoxData();
                boxData.setBoxNum(boxNum);
                boxData.setBoxInterface(one.getBoxInterface());
                boxData.setData(String.valueOf(one.getData()));
                boxData.setCreateTime(StringToDate(DateToString(new Date(), "yyyy-MM-dd"), "yyyy-MM-dd"));
                boxDataMapper.insert(boxData);
            } else {
                BoxData boxData = new BoxData();
                boxData.setBoxNum(boxNum);
                boxData.setBoxInterface(device.getBoxInterface());
                boxData.setData("0.0");
                boxData.setCreateTime(StringToDate(DateToString(new Date(), "yyyy-MM-dd"), "yyyy-MM-dd"));
                boxDataMapper.insert(boxData);
            }
        }
    }
}
